#SPC Export batch files
#-------------------------
library(ggplot2)
library(moments)

#build data method
# items <- fun.buildData(list(data=x,title=""),...)
fun.buildData <- function(..., datas=NULL) {
    itemDatas <- c(list(...), datas)
    return(itemDatas)
}


fun.plot2Img <- function(xdatas=NULL) {
    dataLength <- length(xdatas)

    for (i in 1:dataLength) {
        png(xdatas[[i]]$filePath, width=800, height=500)
        print(fun.buildBar(xdatas[[i]], i))
        dev.off()
    }
}

fun.buildBar <- function(xdatas=NULL, index=NULL) {
    if (is.null(xdatas)) {
        print("No data for building.")
        return(NULL)
    }


    itemData <- xdatas$data
    if(is.null(n) || n == 0) {
        n <- ceiling(sqrt(length(itemData)))
    }

    t <- xdatas$title

    tryCatch({
        sx <- sort(itemData)

        avg <- mean(itemData)
        min <- min(itemData)
        max <- max(itemData)
        std <- sd(itemData)

        kurtosisValue <- kurtosis(itemData)
        skewnessValue <- skewness(itemData)

        #        range <- max(itemData) - min(itemData)

        cl <- c(-3, -2, -1, 0, 1, 2, 3)
        CL <- avg + cl * std
        # set the output variables
        eval(parse(text=paste("CL_", index, "<<- CL", sep="")))
        eval(parse(text=paste("maxValue_", index, "<<- max", sep="")))
        eval(parse(text=paste("minValue_", index, "<<- min", sep="")))
        eval(parse(text=paste("kurtosisValue_", index, "<<- kurtosisValue", sep="")))
        eval(parse(text=paste("skewnessValue_", index, "<<- skewnessValue", sep="")))

        curveXValue <- sort(c(sx, CL))

        xlength <- length(curveXValue)

        nd <- data.frame(d=curveXValue);
        idx <- nd$d %in% CL
        nd$d[idx] <- NA
        ry <- dnorm(curveXValue, mean(curveXValue), sd(curveXValue))

        centerx <- rep(avg, times=xlength)
        sigm_m1 <- rep(CL[3], times=xlength)
        sigm_m2 <- rep(CL[2], times=xlength)
        sigm_p1 <- rep(CL[5], times=xlength)
        sigm_p2 <- rep(CL[6], times=xlength)
        ucl <- rep(CL[7], times=xlength)
        lcl <- rep(CL[1], times=xlength)

        dv <- seq(min, max, by=(max - min)/n)
        barValue <- c(0,as.data.frame(table(cut(sx, dv, include.lowest=T)))[,2])

        yMax <- abs(max(barValue) * 1.1)
        liney <- seq(0,yMax,length=xlength)
        dig <- max(barValue)/max(ry)

        dc <- data.frame(x=nd$d, rx=curveXValue, y=ry, cx=centerx, cy=liney)
        dvt <- round(as.numeric(dv), 6)
        binsize <- (max - min) / n

        p <- ggplot(dc, aes(x=x))
        p <- p + geom_line(aes(x=cx,y=liney), colour="#568A89") + annotate("text",x=CL[4],y=yMax,label="C",size=2.5,hjust=.5,vjust=-.2, colour="#568A89")
        p <- p + geom_line(aes(x=sigm_p1,y=liney), colour="#71843F") + annotate("text",x=CL[5],y=yMax,label="s",size=2.5,hjust=.5,vjust=-.2, colour="#71843F")
        p <- p + geom_line(aes(x=sigm_m1,y=liney), colour="#71843F") + annotate("text",x=CL[3],y=yMax,label="-s",size=2.5,hjust=.5,vjust=-.2, colour="#71843F")
        p <- p + geom_line(aes(x=sigm_m2,y=liney), colour="#71843F") + annotate("text",x=CL[2],y=yMax,label="-2s",size=2.5,hjust=.5,vjust=-.2, colour="#71843F")
        p <- p + geom_line(aes(x=sigm_p2,y=liney), colour="#71843F") + annotate("text",x=CL[6],y=yMax,label="2s",size=2.5,hjust=.5,vjust=-.2, colour="#71843F")
        p <- p + geom_line(aes(x=ucl,y=liney), colour="brown") + annotate("text",x=CL[7],y=yMax,label="UCL",size=2.5,hjust=.5,vjust=-.2, colour="brown")
        p <- p + geom_line(aes(x=lcl,y=liney), colour="brown") + annotate("text",x=CL[1],y=yMax,label="LCL",size=2.5,hjust=.5,vjust=-.2, colour="brown")
        p <- p + geom_histogram(aes(x=x), na.rm=FALSE, binwidth=binsize, fill="#305d8c",colour="white",origin=min,alpha=0.9)
        p <- p + geom_line(aes(x=rx,y=y*dig), colour="red")
        p <- p + scale_x_continuous(breaks=dv,labels=dv)
        p <- p + theme(axis.text.x=element_text(angle=30,size=10,hjust=1,vjust=1))
        p <- p + xlab("")
        p <- p + ylab("Count")
        p <- p + ggtitle(t)
        return (p)
    }, error = function(e) {
        print(e)
        dc <- data.frame(x=c(1:10))
        p3 <- ggplot(dc)+ geom_line(aes(x=0,y=0), colour="red") + ggtitle(t)
        p3 <- p3 +annotate("text",x=0,y=0,label="This item can not be build to a chart.",size=4.5,hjust=.5,vjust=-.2)
        return(p3)
    })

}

#-------------------------
#eval the code and build x data collection : items
#such as: items <- fun.buildData()
eval(parse(text=code))

fun.plot2Img(items)


